package com.ak.socketmq.controller;


import com.ak.socketmq.entity.User;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 这里有前端进行推送
 */
@Controller
@Slf4j
public class JsController {

    @Autowired
    private SimpMessagingTemplate template;

    /**
     * 群发
     *
     * @param
     * @return
     * @throws Exception
     */
    @MessageMapping("/massRequest")//当浏览器向服务端发送请求时，通过@MessageMapping映射/welcome这个地址，类似于@RequestMapping
    @SendTo("/mass/getResponse")//当服务端有消息时，监听了/topic/getResponse的客户端会接收消息
    public String say(User user) throws Exception {
        log.info("群发消息" + user.toString());

        return JSONObject.toJSONString(user);
    }

    /**
     * 单发
     * @param user
     * @return
     */
    @MessageMapping("/aloneRequest")
    public String alone(User user) {
        log.info("前端单独发" + user.toString());
        template.convertAndSendToUser(user.getTo() + "", "/alone/getResponse", user.getMessage());
        return JSONObject.toJSONString(user);
    }
}
